package com.ruoqing.admin.api.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoqing.admin.api.LogHandleService;
import com.ruoqing.admin.feign.AsyncLogServiceFeign;
import com.ruoqing.core.constant.Constants;
import com.ruoqing.core.domain.rqlog.LogEntity;
import com.ruoqing.core.dto.log.LogPageDto;
import com.ruoqing.core.enums.RedisEntityEnum;
import com.ruoqing.core.vo.log.LogResponseVo;
import com.ruoqing.utils.common.BeanSetterUtils;
import com.ruoqing.utils.common.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
	* @author YaoXian
	* @title: LogHandleServiceImpl
	* @projectName ruoxi-blog
	* @description: 若兮微服务 - 后台管理中心 - 管理员操作日志业务层实现类
	* @date 2020-12-09 20:19
	*/
@Slf4j
@Service
public class LogHandleServiceImpl implements LogHandleService {
		
		@Resource
		private AsyncLogServiceFeign asyncLogServiceFeign;
		
		@Resource
		private RedisTemplate<String,LogPageDto> redisTemplate;
		
		public static List<String> redisKeys = new LinkedList<String>();
		
		@Override
		public LogPageDto selectLogByPage(int currentPage, int pageSize) {
				LogPageDto pageDto = redisTemplate.boundValueOps(currentPage + RedisEntityEnum.redis_baseLog.toString()).get();
				if (StringUtils.isEmpty(pageDto)) {
						Page<LogEntity> page = asyncLogServiceFeign.selectLogByPage(currentPage, pageSize);
						LogPageDto logPageDto = new LogPageDto();
						BeanSetterUtils.setPageAttributes(logPageDto,page);
						logPageDto.setList(page.getRecords());
						redisTemplate.boundValueOps(currentPage+RedisEntityEnum.redis_baseLog.toString()).set(logPageDto,30, TimeUnit.MINUTES);
						redisKeys.add(currentPage+RedisEntityEnum.redis_baseLog.toString());
					 pageDto = logPageDto;
						log.info("从MySQL数据库中取分页log信息");
				}else {
						log.info("从Redis缓存中取分页log信息");
						RedisUtils.closeRedisConnection(redisTemplate);
				}
				return pageDto;
		}
		
		@Override
		public LogResponseVo deleteBaseLog(Integer logId) {
				String status;
				String msg;
				if (!StringUtils.isEmpty(logId)){
						Integer result = asyncLogServiceFeign.deleteBaseLog(logId);
						if (result > 0){
								status = Constants.responseOk;
								msg = "删除基础日志成功!";
								removeRedisLog(redisKeys);
						}else {
								status = Constants.responseError;
								msg = "删除基础日志失败,请稍后重试!";
						}
				}else {
						status = Constants.responseError;
						msg = "参数为空!";
				}
				return LogResponseVo.buildLogResponseVo(status,msg);
		}
		
		@Override
		public void removeRedisLog(List<String> redisKeys) {
				redisTemplate.delete(redisKeys);
				while (redisKeys.size() > 0){
						redisKeys.remove(0);
				}
		}
}
